import { Observable } from 'rxjs';
import { BaseManager } from './../libs/rxjs/cc3/BaseManager';
import { _decorator, color, director, System } from 'cc';
import { DevConfig } from './DevConfig';
import { Timer } from '../libs/rxjs/cc3/CreatorSchedule';
import { sys } from 'cc';
import { applovin_sdk_m } from './SDK/AppLovinCocosSDKManager';
import { udm } from './UserDataManager';
import { StageInfo } from '../../ab_lobby/scripts/game/basic';
import { gm } from './GameManager';
import { timem } from './TimeManager';
import { thinking_sdk_m } from './SDK/ThinkingCocosSDKManager';
const { ccclass, property } = _decorator;


@ccclass('AdsManager')
export class AdsManager extends BaseManager {

    public static instance: AdsManager;
    static ID = 'ads_system';
    get logColorOverride() { return color().fromHEX('#EECCDD') };

    static registerSystem() {
        director.unregisterSystem(director.getSystem(AdsManager.ID));
        director.registerSystem(AdsManager.ID, adsm, System.Priority.MEDIUM);
        adsm.init();
    }

    onInitManager() {
        this.log('onInitManager', this.timestamp);
    }

    showRewardAds(flag: string): Observable<string> {
        return new Observable(observer => {
            if (DevConfig.ADS_REWARDS_AUTO_PASSED || !sys.isNative) {
                globalThis.LobbyManager.instance.customLoadingReasons.add(`ads_${flag}`);
                Timer(2).subscribe(_ => {
                    globalThis.LobbyManager.instance.customLoadingReasons.delete(`ads_${flag}`);
                    observer.nextAndComplete('success');
                });
            } else {
                // TODO: 接入广告SDK

                if (sys.isNative) {
                    if (sys.platform == sys.Platform.IOS) {
                        globalThis.LobbyManager.instance.customLoadingReasons.add(`ads_${flag}`);
                        applovin_sdk_m.requestIsReadyRewardedAd().subscribe(isReady => {
                            if (isReady) {
                                this.log('@isReady1');
                                applovin_sdk_m.requestShowRewardedAd().subscribe(didReward => {
                                    globalThis.LobbyManager.instance.customLoadingReasons.delete(`ads_${flag}`);
                                    if (didReward) {
                                        observer.nextAndComplete('success');
                                        globalThis.LobbyManager.instance.frontTipShow('Got reward!');
                                    } else {
                                        observer.nextAndComplete('failed');
                                        globalThis.LobbyManager.instance.frontTipShow('Skip the Ads.');
                                    }
                                });
                            } else {
                                this.log('@isReady2');
                                globalThis.LobbyManager.instance.customLoadingReasons.delete(`ads_${flag}`);
                                globalThis.LobbyManager.instance.frontTipShow('Rewarded not ready.');
                                observer.nextAndComplete('not_ready');
                            }
                        });

                    } else {
                        globalThis.LobbyManager.instance.customLoadingReasons.add(`ads_${flag}`);
                        Timer(2).subscribe(_ => {
                            globalThis.LobbyManager.instance.customLoadingReasons.delete(`ads_${flag}`);
                            observer.nextAndComplete('success');
                        });
                    }
                }
            }
        });

        // globalThis.LobbyManager.instance.frontTipShow('Play ads Failed!');
        // observer.nextAndComplete('failed');
    }

    // 返回空表示需要播放
    interstitialConditionFailReason(stageInfo?: StageInfo): { reason: string, param?: any } { // 插屏广告条件判断
        stageInfo = stageInfo ?? gm.stageInfo.value;
        if (udm.noAds.value == 0) { // 条件：没买去广告
            if (!udm.isNew.value) { // 条件：不是新用户
                if (stageInfo.stageId >= DevConfig.INTERSTITIALAD_FROM_STAGE_NUM) { // 条件：大于等于x关

                    let firstLoginDayAt = new Date(udm.firstLoginAt.value);
                    firstLoginDayAt.setHours(0, 0, 0, 0);
                    let nowDayAt = timem.getCurrentDate();
                    nowDayAt.setHours(0, 0, 0, 0);
                    this.log('nowDayAt/firstLoginDayAt', nowDayAt.valueOf(), firstLoginDayAt.valueOf());

                    if (nowDayAt.valueOf() > firstLoginDayAt.valueOf()) { // 条件：需要隔天
                        let CD = undefined;
                        if (udm.interstitialAt.value != null) {
                            CD = (timem.now() - udm.interstitialAt.value) / 1000;
                        }
                        this.log('interstitialAd CD:', CD, 'need greator than:', DevConfig.INTERSTITIALAD_CD);
                        if (CD == null || CD >= DevConfig.INTERSTITIALAD_CD) { // 条件:需要CD
                            return { reason: null };
                        } else {
                            return { reason: 'cd', param: CD };
                        }
                    } else {
                        return { reason: 'first_day' };
                    }
                } else {
                    return { reason: 'stage_num' };
                }
            } else {
                return { reason: 'new_user' }
            }
        }
        return { reason: 'noads' };
    }

    tryShowInterstitialAds(stageInfo?: StageInfo, interstitialAdsType?: string) {
        stageInfo = stageInfo ?? gm.stageInfo.value;
        gm.currentInterstitialAdsType.value = interstitialAdsType;
        let result = adsm.interstitialConditionFailReason(stageInfo);
        if (result?.reason == null) {
            applovin_sdk_m.requestIsReadyInterstitialAd().subscribe(isReady => {
                thinking_sdk_m.requestTrack('Ads_Interstitial_Stage', {
                    AdsType: gm.currentInterstitialAdsType.value,
                    Level_ID: stageInfo.stageId,
                    Times: udm.interstitialAdTimes.value,
                    CD: result.param ?? 0,
                    CD_Status: "CD_Enough",
                    ad_progress: isReady ? 'Load' : 'LoadFail',
                    IsNew: udm.isNew.value
                });
                if (isReady) {
                    thinking_sdk_m.requestTrack('Ads_Interstitial_Show', {
                        AdsType: gm.currentInterstitialAdsType.value,
                        Level_ID: stageInfo.stageId,
                        Times: udm.interstitialAdTimes.value,
                        IsNew: udm.isNew.value
                    });
                    applovin_sdk_m.stageNum.value = stageInfo.stageId;
                    applovin_sdk_m.requestShowInterstitialAd();
                }
            });
        } else {
            if (result?.reason == 'cd') {
                applovin_sdk_m.requestIsReadyInterstitialAd().subscribe(isReady => {
                    thinking_sdk_m.requestTrack('Ads_Interstitial_Stage', {
                        AdsType: gm.currentInterstitialAdsType.value,
                        Level_ID: stageInfo.stageId,
                        Times: udm.interstitialAdTimes.value,
                        CD: result.param ?? 0,
                        CD_Status: "CD_Low",
                        ad_progress: isReady ? 'Load' : 'LoadFail',
                        IsNew: udm.isNew.value
                    });
                });
            }
        }
    }

}
globalThis.AdsManager = AdsManager;

export const adsm = AdsManager.instance = new AdsManager();